<?php


namespace plugin\exportcenter\app\service;


use app\admin\system\logic\AdminLogic;
use plugin\exportcenter\app\model\Export;
use support\Container;
use support\exception\BadException;
use support\service\MqClient;
use support\utils\LockUtil;
use support\utils\Time;
use think\db\exception\DbException;

class ExportService
{
    /**
     * @param $name
     * @param $action
     * @param $export_params
     * @throws BadException
     * @throws DbException
     */
    static function export($name, $action, $export_params)
    {
        LockUtil::tryLock("export:" . request()->uid, function () use ($name, $action, $export_params) {
            $count = Export::where([
                'created_id' => request()->uid,
                'action' => $action,
                'status' => [Export::STATUS_NORMAL, Export::STATUS_EXPORT_ING],
            ])->count();
            if ($count > 0) {
                throw new BadException("已存在正在导出的任务,请等待导出稍后再试");
            }
            $user = AdminLogic::getCurrentLogicAdmin(request()->uid);
            $id = Export::insertGetId([
                'name' => $name,
                'created_id' => request()->uid,
                'created_name' => $user['nickname'] ?? "",
                'action' => $action,
                'create_time' => Time::now(),
                'export_params' => json_encode($export_params),
            ]);
            Container::get(MqClient::class)->send("export-csv", [
                'id' => $id,
            ]);
        });

    }
}